const userListEle = document.querySelector('#user-list') //tbody
const baseUrl = "http://47.105.173.95:3000/api/users"
let currentPage = 1;
let pageCount = 1
let gPageSize = 20

/*-----------------------网络请求相关------------------------- */
function ajaxGet(url, callback) {
    //#1.创建xhr实例
    const xhr = new XMLHttpRequest()
    //#2.初始化一个请求
    xhr.open('GET', url)
    //#3.发送请求
    xhr.send()
    //#4.监听xhr的readystate的变化，使用onreadystatechange函数
    xhr.onreadystatechange = function (e) {
        if (xhr.readyState == 4 && xhr.status == 200) {
            const res = JSON.parse(xhr.responseText)
            if (typeof callback == 'function') {
                callback(res)
            }
        }
    }
};
function ajaxPost(url,data,callback) {
    const dataStr = JSON.stringify(data)
    const xhr = new XMLHttpRequest()
    xhr.open('POST', url)
    //设置请求头
    xhr.setRequestHeader("Content-Type", "application/json")
    xhr.send(dataStr)
    //#4.监听xhr的readystate的变化，使用onreadystatechange函数
    xhr.onload = function(e){
        if (xhr.status == 200) {
            const res = JSON.parse(xhr.responseText)
            if (typeof callback == 'function') {
                callback(res)
            }
        }
    }
};
function ajaxPatch(url,data,callback) {
    const dataStr = JSON.stringify(data)
    const xhr = new XMLHttpRequest()
    xhr.open('PATCH', url)
    //设置请求头
    xhr.setRequestHeader("Content-Type", "application/json")
    xhr.send(dataStr)
    //#4.监听xhr的readystate的变化，使用onreadystatechange函数
    xhr.onload = function(e){
        if (xhr.status == 200) {
            const res = JSON.parse(xhr.responseText)
            if (typeof callback == 'function') {
                callback(res)
            }
        }
    }
};
//根据传入的参数获取用户数据
function getUsers(params, callback) {
    const query = joinParams(params)
    const url = baseUrl + query
    ajaxGet(url, function (res) {
        //如果成功获取到用户数据，则回调
        if (res.code == 0) {
            const results = res.results
            callback(results)
        } else {
            //否则则弹出提示框
            alert(res.msg)
        }
    })
}

function joinParams(params) {
    let query = '?'
    for (let key in params) {
        query += `${key}=${params[key]}&`
    }
    return query.slice(0, -1)
}

/*-----------------设置用户列表相关-------------------- */
//初始化用户列表数据
(function initUsers() {
    getUsers({ _page: 1, _limit: 20 }, function (results) {
        renderUserList(results.users)
        pageCount = results.page_count
        currentPage = results.page
        renderPagination(pageCount)
        pageActive(currentPage)

    })
})()
//把用户数据渲染到表格
function renderUserList(users) {
    const html = users.map(user => {
        return `
                <tr>
                    <th>${user.id}</th>
                    <th>${user.username}</th>
                    <th>${user.gender == 0 ? '男' : '女'}</th>
                    <th>${user.telephone}</th>
                    <th>${user.email}</th>
                    <th>
                        <button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#modal-detail" data-id=${user.id} data-type="detail">详细</button>
                        <button type="button" class="btn btn-danger btn-sm" data-id=${user.id} data-type="delete">删除</button>
                    </th>
                </tr>`
    }).join('')
    userListEle.innerHTML = html
};
let  gCurrentUser;
//给用户列表操作栏的按钮绑定事件
(function bindUserListButton() {
    userListEle.addEventListener('click', function (e) {
        const clickElement = e.target
        if (clickElement.tagName == 'BUTTON') {
            if (clickElement.dataset.type == 'detail') {
                //点击的是详细按钮
                setModalFormState('view')
                const id = clickElement.dataset.id //获取点击的详细按钮对应的id
                getUsers({ id: id }, function (results) {
                    setFormValue(detailFormOption, results.users[0])
                    gCurrentUser = results.users[0]
                })
            } else if (clickElement.dataset.type == 'delete') {
                //删除操作
                //TODO
            }
        }
    });
})()


/*------------------用户详细表单相关---------------------- */
//表单配置文件
const detailFormOption = {
    id: {
        selector: '#u-id',//选择器
        dataKey: "id",//对应的返回数据中的键
    },
    username: {//字段名称
        selector: '#username',//选择器
        dataKey: "username",//对应的返回数据中的键
        element: null //输入框元素，由后面的initDetailFormElement函数获取并挂载到此处
    },
    email: {
        selector: '#email',
        dataKey: 'email'
    },
    nickname: {
        selector: "#nickname",
        dataKey: "nicheng"
    },
    telephone: {
        selector: '#telephone',
        dataKey: "telephone"
    },
    birthday: {
        selector: '#birthday',
        dataKey: "birthday"
    },
    gender: {
        selector: "[name=gender]",//checkbox和radio推荐使用name做为选择器
        dataKey: 'gender'
    },
    state: {
        selector: "#state",
        dataKey: 'state'
    },
    addr: {
        selector: "#addr",
        dataKey: 'address'
    },
    loginTime: {
        selector: "#login-time",
        dataKey: 'time'
    },
    intro: {
        selector: "#intro",
        dataKey: 'intro'
    },
    permission: {
        selector: "[name='permission']",
        dataKey: 'permission'
    }
};

//把所有字段对应的输入框找到并挂载到detailFormFieldElement里面
(function mountElementTodetailFormOption() {
    for (let field in detailFormOption) {
        const fieldObj = detailFormOption[field]
        const selector = fieldObj.selector
        const elements = document.querySelectorAll(selector)
        if(!elements) {throw Error(`${field}字段的选择器:${selector}，找不到元素`)}
        if (elements.length > 1) {
            //转换成数组
            fieldObj.element = [...elements]
        } else {
            fieldObj.element = elements[0]
        }
    }
})()

/*------------------------------表单通用------------------------------ */
//设置表单的数据
function setFormValue(formOption, data) {
    for (let field in formOption) {
        const element = formOption[field].element
        const fieldKey = formOption[field].dataKey
        const fieldValue = data[fieldKey]
        if(!element) continue
        if (element) {
            if (Array.isArray(element)) {
                if (element[0].type == "radio") {
                    element.forEach(item => {
                        if (item.value == fieldValue) {
                            item.checked = true
                        }
                    })
                } else if (element[0].type == 'checkbox') {
                    const valueList = fieldValue.split(',')
                    element.forEach(item => {
                        if (valueList.includes(item.value)) {
                            item.checked = true
                        }
                    })
                }
            } else {
                element.value = fieldValue
            }
        }
    }
}
//获取表单的数据
function getFormValue(formOption = detailFormOption) {
    let data = {}
    for (let field in formOption) {
        const element = formOption[field].element
        const fieldKey = formOption[field].dataKey
        if (!element) continue
        if (!Array.isArray(element)) {
            const fieldValue = element.value
            data[fieldKey] = fieldValue
        } else {
            let fieldValueList = []
            element.forEach(item => {
                if (item.checked) {
                    fieldValueList.push(item.value)
                }
            })
            data[fieldKey] = fieldValueList.join(',')
        }
    }
    return data
}
//清除表单数据
function clearFormValue(formOption = detailFormOption) {
    for (let field in formOption) {
        const element = formOption[field].element
        if (!element) continue
        if (!Array.isArray(element)) {
            element.value = ''
        } else {
            element.forEach(item => {
                item.checked = false
            })
        }
    }
}

/*-------------------------分页相关----------------------------------- */
const paginationEle = document.querySelector('.pagination');
const pageSizeEle = document.getElementById('page-size');
(function bindPagination() {
    paginationEle.onclick = function (e) {
        //阻止事件默认行为
        e.preventDefault();
        const clickElement = e.target
        const page = clickElement.dataset.page//1,2,3,next,prev     
        handleSwitchpage(page, gPageSize)
    }
    pageSizeEle.onchange = function (e) {
        console.log('pagesize改变了')
        console.log(this.value)
        const targetPageSize = this.value
        //请求网络
        handleSwitchpage(currentPage, targetPageSize)
    }

})()

//负责切换到对应的页面，并把数据渲染到网页
function handleSwitchpage(page, pageSize = gPageSize) {
    let targetPage;
    if (!isNaN(page)) {
        targetPage = page
    } else if (page == 'next') {
        if (currentPage >= pageCount) {  return }
        targetPage = currentPage + 1
    } else if (page == 'prev') {
        if (currentPage <= 1) { return }
        targetPage = currentPage - 1
    }
    //如果每页数量在改变，自动跳转到第一页
    if (pageSize != gPageSize) {
        targetPage = 1
    }
    //根据页面和每页的数量请求页码对应的用户数据
    getUsers({ _page: targetPage, _limit: pageSize }, function (results) {
        renderUserList(results.users)
        renderPagination(results.page_count)
        pageActive(results.page)
        currentPage = parseInt(targetPage)
        pageCount = parseInt(results.page_count)
        gPageSize = parseInt(pageSize)


    })
    //把数据渲染到页面
}
//激活当且页码
function pageActive(page) {
    const pageLis = paginationEle.querySelectorAll('li')
    const nextPageEle = paginationEle.querySelector('.page-next')
    const prevPageEle = paginationEle.querySelector('.page-prev')
    // console.log(pageLis)
    pageLis.forEach(li => {
        if (li.dataset.page == page) {
            li.classList.add('active')
        } else {
            li.classList.remove('active')
        }
    })
    if (page >= pageCount) {
        nextPageEle.classList.add('disabled')
    } else if (page <= 1) {
        prevPageEle.classList.add('disabled')
    } else {
        nextPageEle.classList.remove('disabled')
        prevPageEle.classList.remove('disabled')
    }

}
//根据页面的总数动态的生成分页器
function renderPagination(pageCount,activePage=1) {
    let lis = ''
    for (i = 1; i <= pageCount; i++) {
        lis += `<li class="${i == activePage ? 'active' : ''}" data-page=${i}><a href="#" data-page=${i}>${i}</a></li>`
    }

    const html = `
    <li class="page-prev">
        <a href="#" aria-label="Previous" data-page="prev">
            <span aria-hidden="true" data-page="prev">&laquo;</span>
        </a>
    </li>
    ${lis}
    <li class="page-next">
        <a href="#" aria-label="Next" data-page="next">
            <span aria-hidden="true" data-page="next">&raquo;</span>
        </a>
    </li>`
    paginationEle.innerHTML = html

};
/*---------------------------搜索用户-----------------------------------------*/
(function bindSearch() {
    const searchBtn = document.getElementById('search-btn')
    const userIdIpt = document.getElementById('user-id')
    searchBtn.onclick = function (e) {
        e.preventDefault()
        const userId = userIdIpt.value
        getUsers({ id: userId }, function (results) {
            const user = results.users[0]
            //1.打开模态框
            $("#modal-detail").modal('show')
            //2.把数据设置给表单
            setFormValue(detailFormOption, user)
        })
    }
})();
/*-----------------------------添加用户-----------------------------------------*/
let gFormState = 'read';//表单的状态，read,write
(function bindAddUser() {
    const addUserBtn = document.getElementById('add-user')
    addUserBtn.onclick = function (e) {
        e.preventDefault()
        $("#modal-detail").modal('show') 
        setModalFormState('add')
    }
})()

//设置表单的状态，读，写。read,write
function setFormState(state, formOption = detailFormOption) {
    let flag;
    if (state == 'read') {
        flag = true
    } else if (state == 'write') {
        flag = false
    } else {
        throw Error('表单状态不合法')
    }
    for (field in formOption) {
        const element = formOption[field].element
        if (!element) continue
        if (!Array.isArray(element)) {
            if (element.type == 'checkbox' || element.type == 'radio') {
                element.disabled = flag
            } else {
                element.readOnly = flag
            }
        } else {
            element.forEach(item => {
                item.disabled = flag
            })
        }
    }
    gFormState = state
};
(function bindnOkBtn(){
    const okBtn = document.getElementById('ok-btn')
    okBtn.onclick = function(){
        //判断模态框表单整体状态，根据状态做出对应的事情
        if(gModalFormState == 'view'){
            setModalFormState("update")
        }else if(gModalFormState == 'update'){
            //TODO
            //更新用户信息
            const newUserData = getFormValue()
            gCurrentUser
            let userDiff = diff(newUserData,gCurrentUser)
            const url = baseUrl + '/' + gCurrentUser.id
            ajaxPatch(url,userDiff,function(res){
                alert('修改用户成功')
                setModalFormState("view")
            })
            

        }else if(gModalFormState == 'add'){
            //添加用户
            const user = getFormValue()
            console.log(user)
            ajaxPost(baseUrl,user,function(res){
                alert('新增用户成功！')
                setModalFormState('view')
            })
        }else{
            throw Error(`全局变量gModalFormState:${gModalFormState}为不合法状态`)
        }
    }
})()
function diff(obj1,obj2){
    const res = {}
    for(let key in obj1){
        if(obj1[key] != obj2[key]){
            res[key] = obj1[key]
        }
    }
    return res
}
let gModalFormState = 'view'//view,update,add
function setModalFormState(state){
    let modalOpt = {
        selector:"#modal-detail" 
    }
    if(state == "view"){
        setFormState('read')
        //设置模态框
        modalOpt.title = "查看用户信息"
        modalOpt.okBtn = {
            text : "修改",
            type : 'warning'
        }         
    }else if(state == 'update'){
        setFormState('write')
        modalOpt.title = "修改用户信息"
        modalOpt.okBtn = {
            text : "保存",
            type : 'danger'
        }
    }else if(state == 'add'){
        clearFormValue()
        setFormState('write')
        modalOpt.title = "新增用户信息"
        modalOpt.okBtn = {
            text : "新增",
            type : 'success'
        }
    }else{
        throw Error(`给ModalFormState设置的状态${state}不合法，只能设置view,update,add`)
    }
    setModal(modalOpt)
    //更新全局变量
    gModalFormState = state
}
/*-----------------------模态框通用---------------------------- */
//配置文件格式
// let option = {
//     selector:'模态框选择器',
//     element:'模态框元素',
//     title:'模态框标题',
//     content:'模态框内容',
//     okBtn:{
//         text:'okBtn的文字',
//         type:'按钮显示类型',
//         show:'true代表显示，false不显示，默认true',
//         data:{},
//         class:[]
//     },
//     cancelBtn:{
//         text:'okBtn的文字',
//         type:'按钮显示类型',
//         show:'true代表显示，false不显示，默认true',
//         data:{},
//         className:[]//'a'/['a','b']
//     }
// }
//模态框设置
function setModal(option){
    let element;
    if(option.element){
        element = option.element
    }else{
        if(!option.selector) throw Error(`配置文件必须填写selector或者element`)
        element = document.querySelector(option.selector)
        if(!element) throw Error(`没有找到模态框元素`)
    }
    if(option.title != undefined){
        element.querySelector('.modal-title').innerText = option.title
    }
    if(option.content != undefined){
        element.querySelector('.modal-body').innerHTML = option.content
    }
    if(option.okBtn){
        const okBtnEle = document.querySelector('.ok-btn')
        if(option.okBtn.text != undefined){okBtnEle.innerText = option.okBtn.text}
        if(option.okBtn.show == false){
            okBtnEle.style.display = 'none'
        }else{
            okBtnEle.style.display = 'inline-block'
        }
        if(option.okBtn.type){
            let className = okBtnEle.className
            let newClassName = className.replace(/btn-\w+/,`btn-${option.okBtn.type}`)
            okBtnEle.className = newClassName
        }
        if(typeof option.okBtn.data == 'object'){
            const data = option.okBtn.data
            for(key in data){
                okBtnEle.dataset[key] = data[key]
            }
        }
        if( option.okBtn.className){
            const className = option.okBtn.className
            if(typeof className == 'string'){
                okBtnEle.classList.add(className)
            }else if(Array.isArray(className)){
                className.forEach(item => {
                    okBtnEle.classList.add(item)
                })
            }
        }
    }
    if(option.cancleBtn){
        const cancleBtnEle = document.querySelector('.cancle-btn')
        if(option.cancleBtn.text != undefined){cancleBtnEle.innerText = option.cancleBtn.text}
        if(option.cancleBtn.show == false){
            cancleBtnEle.style.display = 'none'
        }else{
            cancleBtnEle.style.display = 'inline-block'
        }
        if(option.cancleBtn.type){
            let className = cancleBtnEle.className
            let newClassName = className.replace(/btn-\w+/,`btn-${option.cancleBtn.type}`)
            cancleBtnEle.className = newClassName
        }
        if(typeof option.cancleBtn.data == 'object'){
            const data = option.cancleBtn.data
            for(key in data){
                cancleBtnEle.dataset[key] = data[key]
            }
        }
        if( option.cancleBtn.className){
            const className = option.cancleBtn.className
            if(typeof className == 'string'){
                cancleBtnEle.classList.add(className)
            }else if(Array.isArray(className)){
                className.forEach(item => {
                    cancleBtnEle.classList.add(item)
                })
            }
        }
    }
}

/*
 触发点击事件 -> 请求数据 -> 拿到返回的数据并解析 -> 渲染到网页
*/